package com.xbongbong.saas.service.impl;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.xbongbong.i18n.util.I18nMessageUtil;
import com.xbongbong.paas.constant.PaasConstant;
import com.xbongbong.paas.domain.entity.PaasMenuEntity;
import com.xbongbong.paas.elasticsearch.model.PaasEsModel;
import com.xbongbong.paas.elasticsearch.pojo.XbbAggregatedPage;
import com.xbongbong.paas.elasticsearch.pojo.dto.InsertDTO;
import com.xbongbong.paas.elasticsearch.util.EsUtil;
import com.xbongbong.paas.elasticsearch.util.XbbElasticsearchRestTemplate;
import com.xbongbong.paas.enums.DelEnum;
import com.xbongbong.paas.enums.IndexTypeEnum;
import com.xbongbong.sys.help.PackageHelp;
import com.xbongbong.paas.log.MongoLogHelp;
import com.xbongbong.paas.model.PaasMenuModel;
import com.xbongbong.paas.pojo.ButtonPojo;
import com.xbongbong.paas.redis.PaasRedisHelper;
import com.xbongbong.paas.redis.RedisPrefixConstant;
import com.xbongbong.paas.toolbox.exception.XbbException;
import com.xbongbong.paas.toolbox.helper.PageHelper;
import com.xbongbong.paas.toolbox.util.CollectionsUtil;
import com.xbongbong.paas.toolbox.util.DateTimeUtil;
import com.xbongbong.paas.toolbox.util.StringUtil;
import com.xbongbong.paas.toolbox.wrap.BaseDTO;
import com.xbongbong.paas.toolbox.wrap.BaseVO;
import com.xbongbong.paas.toolbox.wrap.UserVO;
import com.xbongbong.pro.constant.CommonConstant;
import com.xbongbong.pro.constant.ElasticConstant;
import com.xbongbong.pro.enums.PackageTypeEnum;
import com.xbongbong.pro.enums.errorcodes.BiErrorCodeEnum;
import com.xbongbong.pro.enums.errorcodes.SystemErrorCodeEnum;
import com.xbongbong.pro.enums.permission.enums.ProPermissionAliasEnum;
import com.xbongbong.pro.knowledge.base.pojo.CataloguePojo;
import com.xbongbong.pro.knowledge.base.pojo.KnowledgeBaseCountPojo;
import com.xbongbong.pro.knowledge.base.pojo.KnowledgeHighlighterPojo;
import com.xbongbong.pro.knowledge.base.pojo.OptionalRangePojo;
import com.xbongbong.pro.knowledge.base.pojo.TagPojo;
import com.xbongbong.pro.knowledge.base.pojo.TagSortPojo;
import com.xbongbong.pro.knowledge.base.pojo.dto.KnowledgeBaseBatchDeleteDTO;
import com.xbongbong.pro.knowledge.base.pojo.dto.KnowledgeBaseDTO;
import com.xbongbong.pro.knowledge.base.pojo.dto.KnowledgeBaseDetailDTO;
import com.xbongbong.pro.knowledge.base.pojo.dto.KnowledgeBaseUpdateDTO;
import com.xbongbong.pro.knowledge.base.pojo.dto.KnowledgeCatalogueAddDTO;
import com.xbongbong.pro.knowledge.base.pojo.dto.KnowledgeCatalogueDelDTO;
import com.xbongbong.pro.knowledge.base.pojo.dto.KnowledgeCatalogueNameLikeDTO;
import com.xbongbong.pro.knowledge.base.pojo.dto.KnowledgeCatalogueSortDTO;
import com.xbongbong.pro.knowledge.base.pojo.dto.KnowledgeCatalogueUpdateDTO;
import com.xbongbong.pro.knowledge.base.pojo.dto.KnowledgeContentDTO;
import com.xbongbong.pro.knowledge.base.pojo.dto.KnowledgeHighlighterListDTO;
import com.xbongbong.pro.knowledge.base.pojo.dto.KnowledgeShowDTO;
import com.xbongbong.pro.knowledge.base.pojo.vo.KnowledgeBaseListVO;
import com.xbongbong.pro.knowledge.base.pojo.vo.KnowledgeBaseVO;
import com.xbongbong.pro.knowledge.base.pojo.vo.KnowledgeCatalogueListVO;
import com.xbongbong.pro.knowledge.base.pojo.vo.KnowledgeCloudCallRedirectsVO;
import com.xbongbong.pro.knowledge.base.pojo.vo.KnowledgeDetailsVO;
import com.xbongbong.pro.knowledge.base.pojo.vo.KnowledgeHighlighterListVO;
import com.xbongbong.pro.log.pojo.DetailLogPojo;
import com.xbongbong.pro.thread.ThreadPoolBeanConfig;
import com.xbongbong.saas.constant.BasicConstant;
import com.xbongbong.saas.constant.StringConstant;
import com.xbongbong.saas.domain.entity.KnowledgeBaseEntity;
import com.xbongbong.saas.domain.entity.KnowledgeCatalogueEntity;
import com.xbongbong.saas.domain.entity.KnowledgeDataEntity;
import com.xbongbong.saas.domain.entity.KnowledgeTagEntity;
import com.xbongbong.saas.enums.KnowledgeErrorCodeEnum;
import com.xbongbong.saas.enums.OperateModuleTypeEnum;
import com.xbongbong.saas.enums.OperateTypeEnum;
import com.xbongbong.saas.enums.base.KnowledgeDataBaseEnum;
import com.xbongbong.saas.enums.business.KnowledgeDataEnum;
import com.xbongbong.saas.help.KnowledgeBaseHelp;
import com.xbongbong.saas.model.KnowledgeBaseModel;
import com.xbongbong.saas.model.KnowledgeCatalogueModel;
import com.xbongbong.saas.model.KnowledgeDataModel;
import com.xbongbong.saas.model.KnowledgeTagModel;
import com.xbongbong.saas.service.KnowledgeBaseService;
import com.xbongbong.sys.domain.entity.UserConfigEntity;
import com.xbongbong.sys.enums.UserConfigEnum;
import com.xbongbong.sys.model.UserConfigModel;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.common.text.Text;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightField;
import org.elasticsearch.search.sort.SortOrder;
import org.springframework.data.domain.PageRequest;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Set;
import java.util.stream.Collectors;

import static org.elasticsearch.index.query.QueryBuilders.boolQuery;
import static org.elasticsearch.index.query.QueryBuilders.matchQuery;
import static org.elasticsearch.index.query.QueryBuilders.termQuery;
import static org.elasticsearch.index.query.QueryBuilders.termsQuery;

/**
 * @Author mingliang
 * @Description 知识库相关接口
 * @Date 2022/6/24 15:36
 **/
@Slf4j
@Service("knowledgeBaseService")
public class KnowledgeBaseServiceImpl implements KnowledgeBaseService {

    @Resource
    private KnowledgeBaseModel knowledgeBaseModel;
    @Resource
    private KnowledgeCatalogueModel knowledgeCatalogueModel;
    @Resource
    private KnowledgeDataModel knowledgeDataModel;
    @Resource
    private MongoLogHelp mongoLogHelp;
    @Resource
    private PackageHelp packageHelp;
    @Resource
    private KnowledgeTagModel knowledgeTagModel;
    @Resource
    private XbbElasticsearchRestTemplate xbbElasticsearchRestTemplate;
    @Resource
    private PaasRedisHelper paasRedisHelper;
    @Resource
    private KnowledgeBaseHelp knowledgeBaseHelp;
    @Resource
    private PaasMenuModel paasMenuModel;
    @Resource
    private PaasEsModel paasEsModel;
    @Resource
    private UserConfigModel userConfigModel;
    @Resource
    private ThreadPoolBeanConfig threadPoolBeanConfig;



    @Override
    public KnowledgeBaseListVO knowledgeBaseList(BaseDTO baseDTO) throws XbbException {
        String userId = baseDTO.getUserId();
        String corpid = baseDTO.getCorpid();
        UserVO loginUser = baseDTO.getLoginUser();
        String department = loginUser.getDepartment();
        List<String> departmentList = new ArrayList<>();
        if (StringUtil.isNotEmpty(department)){
            departmentList = JSONArray.parseArray(department, String.class);
        }
        Map<String, Object> map = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        map.put(StringConstant.CORPID, baseDTO.getCorpid());
        map.put(StringConstant.DEL, DelEnum.NORMAL.getDel());
        map.put("isDefault", BasicConstant.ONE);
        Integer count = knowledgeBaseModel.getEntitysCount(map);
        // 如果没有默认知识库，则添加默认知识库
        if (count <= BasicConstant.ZERO && paasRedisHelper.checkConcurrentLock(RedisPrefixConstant.KNOWLEDGE_BASE_ADD_DEFAULT, corpid, BasicConstant.THREE, false)) {
            addDefaultKnowledgeBase(baseDTO);
        }
        map.remove("isDefault");
        map.put("orderByStr", " is_default desc ");
        List<KnowledgeBaseEntity> knowledgeBaseEntityList = knowledgeBaseModel.findEntitys(map);
        KnowledgeBaseListVO knowledgeBaseListVO = new KnowledgeBaseListVO();
        List<KnowledgeBaseVO> knowledgeBaseVOList = new ArrayList<>();
        boolean isAdminOrBoss = loginUser.isAdminOrBoss();
        if (CollectionsUtil.isNotEmpty(knowledgeBaseEntityList)) {
            // 将知识条目数据分组统计总个数，存储在knowledgeBaseCountPojoMap中
            Map<Long, Integer> knowledgeBaseCountPojoMap = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
            List<Long> idList = knowledgeBaseEntityList.stream().map(KnowledgeBaseEntity::getId).collect(Collectors.toList());
            List<KnowledgeBaseCountPojo> countByKnowledgeId = knowledgeDataModel.getCountByKnowledgeId(corpid, idList);
            Integer feeType = packageHelp.getFeeType(corpid);
            // 判断知识库是否需要重新选择
            if ((Objects.equals(PackageTypeEnum.ADVANCED.getType(), feeType) && knowledgeBaseEntityList.size() > BasicConstant.THREE) || (Objects.equals(PackageTypeEnum.STANDARD.getType(), feeType) && knowledgeBaseEntityList.size() > BasicConstant.ZERO) && isAdminOrBoss) {
                knowledgeBaseListVO.setIsReselect(BasicConstant.TWO);
            } else if ((Objects.equals(PackageTypeEnum.ADVANCED.getType(), feeType) && knowledgeBaseEntityList.size() > BasicConstant.THREE) || (Objects.equals(PackageTypeEnum.STANDARD.getType(), feeType))&& !isAdminOrBoss) {
                knowledgeBaseListVO.setIsReselect(BasicConstant.THREE);
            } else {
                knowledgeBaseListVO.setIsReselect(BasicConstant.ONE);
            }
            if (CollectionUtils.isNotEmpty(countByKnowledgeId)) {
                countByKnowledgeId.forEach(e -> {
                    knowledgeBaseCountPojoMap.put(e.getKnowledgeBaseId(), e.getCount());
                });
            }
            // 拼接数据
            for (KnowledgeBaseEntity knowledgeBaseEntity : knowledgeBaseEntityList) {
                KnowledgeBaseVO knowledgeBaseVO = new KnowledgeBaseVO();
                String viewConfig = knowledgeBaseEntity.getViewConfig();
                String managerConfig = knowledgeBaseEntity.getManagerConfig();
                //可见用户范围
                Set<String> viewUserIdSet = new HashSet<>();
                //可见部门范围
                Set<String> viewDepartmentIdSet = new HashSet<>();
                Set<String> managerUserIdSet = new HashSet<>();
                if (StringUtil.isNotEmpty(viewConfig) && CollectionsUtil.isNotEmpty(JSONArray.parseArray(viewConfig, OptionalRangePojo.class))) {
                    List<OptionalRangePojo> viewConfigPojoList = JSONArray.parseArray(viewConfig, OptionalRangePojo.class);
                    knowledgeBaseVO.setViewConfig(viewConfigPojoList);
                    if (CollectionsUtil.isNotEmpty(viewConfigPojoList)) {
                        String viewConfigValue = listToString(viewConfigPojoList, viewUserIdSet, viewDepartmentIdSet);
                        knowledgeBaseVO.setViewConfigValue(viewConfigValue);
                    }
                }
                if (StringUtil.isNotEmpty(managerConfig) && CollectionsUtil.isNotEmpty(JSONArray.parseArray(managerConfig, OptionalRangePojo.class))) {
                    List<OptionalRangePojo> managerConfigPojoList = JSONArray.parseArray(managerConfig, OptionalRangePojo.class);
                    knowledgeBaseVO.setManagerConfig(managerConfigPojoList);
                    String managerConfigValue = listToString(managerConfigPojoList, managerUserIdSet, null);
                    knowledgeBaseVO.setManagerConfigValue(managerConfigValue);
                }
                // 如果不是超管，不在可见范围，不在管理员列表，则无法查看
                if (!isAdminOrBoss
                        && (CollectionsUtil.isNotEmpty(viewUserIdSet) && !viewUserIdSet.contains(userId))
                        && (CollectionsUtil.isNotEmpty(managerUserIdSet) && !managerUserIdSet.contains(userId))
                        && (Collections.disjoint(viewDepartmentIdSet, departmentList))) {
                    continue;
                }
                Boolean adminBool = isAdminOrBoss || (CollectionsUtil.isNotEmpty(managerUserIdSet) && managerUserIdSet.contains(userId));
                Boolean updateBool = isAdminOrBoss || (CollectionsUtil.isNotEmpty(managerUserIdSet) && managerUserIdSet.contains(userId) && loginUser.getPermSet().contains(ProPermissionAliasEnum.KNOWLEDGE_BASE_EDIT.getAlias()));
                Boolean deleteBool = isAdminOrBoss || (CollectionsUtil.isNotEmpty(managerUserIdSet) && managerUserIdSet.contains(userId) && loginUser.getPermSet().contains(ProPermissionAliasEnum.KNOWLEDGE_BASE_DELETE.getAlias()));

                knowledgeBaseVO.setId(knowledgeBaseEntity.getId());
                knowledgeBaseVO.setName(knowledgeBaseEntity.getKnowledgeName());
                knowledgeBaseVO.setCount(knowledgeBaseCountPojoMap.getOrDefault(knowledgeBaseEntity.getId(), 0));
                knowledgeBaseVO.setUpdateTime(knowledgeBaseEntity.getUpdateTime());
                knowledgeBaseVO.setIsAdmin(adminBool);
                knowledgeBaseVO.setIfDefault(knowledgeBaseEntity.getIsDefault());
                knowledgeBaseVO.setUpdateBool(updateBool);
                if (Objects.equals(knowledgeBaseEntity.getIsDefault(), 1)) {
                    knowledgeBaseVO.setDeleteBool(false);
                } else {
                    knowledgeBaseVO.setDeleteBool(deleteBool);
                }

                knowledgeBaseVOList.add(knowledgeBaseVO);
            }
        }
        knowledgeBaseListVO.setKnowledgeBaseVOList(knowledgeBaseVOList);
        List<ButtonPojo> topPermissions = new ArrayList<>();
        if (isAdminOrBoss || loginUser.getPermSet().contains(ProPermissionAliasEnum.KNOWLEDGE_BASE_ADD.getAlias())) {
            ButtonPojo buttonPojo = new ButtonPojo();
            buttonPojo.setAttr("add");
            buttonPojo.setIcon("primary");
            buttonPojo.setValue(I18nMessageUtil.getMessage(StringConstant.ADD_KNOWLEDGE_BASE));
            topPermissions.add(buttonPojo);
        }
        UserConfigEntity userConfigEntity = userConfigModel.getByUserId(userId, corpid, UserConfigEnum.KNOWLEDGE_BASE_SHOW.getAlias());
        if (Objects.isNull(userConfigEntity)) {
            knowledgeBaseListVO.setIsShow(Boolean.FALSE);
        } else {
            knowledgeBaseListVO.setIsShow(Objects.equals("1", userConfigEntity.getConfigValue()) ? Boolean.TRUE : Boolean.FALSE);
        }
        knowledgeBaseListVO.setTopPermissions(topPermissions);
        return knowledgeBaseListVO;
    }

    @Override
    public BaseVO addKnowledgeBase(KnowledgeBaseDTO knowledgeBaseDTO) throws XbbException {
        UserVO loginUser = knowledgeBaseDTO.getLoginUser();
        boolean isAdminOrBoss = loginUser.isAdminOrBoss();
        // 判断是否拥有知识库新增权限
        if (!isAdminOrBoss && !loginUser.getPermSet().contains(ProPermissionAliasEnum.KNOWLEDGE_BASE_ADD.getAlias())) {
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100061);
        }
        Map<String, Object> map = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        map.put(StringConstant.CORPID, knowledgeBaseDTO.getCorpid());
        map.put(StringConstant.DEL, DelEnum.NORMAL.getDel());
        map.put("isDefault", BasicConstant.ZERO);
        int noDefaultCount = knowledgeBaseModel.getEntitysCount(map);
        Integer feeType = packageHelp.getFeeType(knowledgeBaseDTO.getCorpid());
        // 套餐校验知识库个
        if (Objects.equals(PackageTypeEnum.STANDARD.getType(), feeType)) {
            throw new XbbException(KnowledgeErrorCodeEnum.API_ERROR_320001.getCode(), String.format(KnowledgeErrorCodeEnum.API_ERROR_320001.getMsg(), "1"));
        } else if (Objects.equals(PackageTypeEnum.ADVANCED.getType(), feeType) && noDefaultCount >= BasicConstant.TWO) {
            throw new XbbException(KnowledgeErrorCodeEnum.API_ERROR_320001.getCode(), String.format(KnowledgeErrorCodeEnum.API_ERROR_320001.getMsg(), "3"));
        } else if (Objects.equals(PackageTypeEnum.ULTIMATE.getType(), feeType) && noDefaultCount >= BasicConstant.FIVE) {
            throw new XbbException(KnowledgeErrorCodeEnum.API_ERROR_320001.getCode(), String.format(KnowledgeErrorCodeEnum.API_ERROR_320001.getMsg(), "6"));
        } else if (noDefaultCount >= BasicConstant.FIVE) {
            throw new XbbException(KnowledgeErrorCodeEnum.API_ERROR_320001.getCode(), String.format(KnowledgeErrorCodeEnum.API_ERROR_320001.getMsg()));
        }
        KnowledgeBaseEntity knowledgeBaseEntity = getEntityByDTO(knowledgeBaseDTO, BasicConstant.ZERO);
        knowledgeBaseModel.insert(knowledgeBaseEntity);
        // 知识库新增记录日志
        String memo = knowledgeBaseDTO.getLoginUserName() + I18nMessageUtil.getMessage(CommonConstant.ADD) + String.format(I18nMessageUtil.getMessage(StringConstant.KNOWLEDGE_BASE_LOG), knowledgeBaseDTO.getName());
        mongoLogHelp.buildLog(knowledgeBaseDTO.getCorpid(), knowledgeBaseDTO.getUserId(), knowledgeBaseDTO.getLoginUserName(), OperateModuleTypeEnum.KNOWLEDGE_BASE,
                OperateTypeEnum.NEW, knowledgeBaseEntity.getId().toString(), knowledgeBaseEntity.getKnowledgeName(), memo, knowledgeBaseDTO.getHttpHeader());
        return new BaseVO();
    }


    @Override
    public BaseVO updateKnowledgeBase(KnowledgeBaseUpdateDTO knowledgeBaseUpdateDTO) throws XbbException {
        KnowledgeBaseEntity baseEntity = knowledgeBaseModel.getByKey(knowledgeBaseUpdateDTO.getId(), knowledgeBaseUpdateDTO.getCorpid());
        if (Objects.isNull(baseEntity)) {
            return new BaseVO();
        }
        // 权限校验
        boolean permissionsBool = permissionsValidation(knowledgeBaseUpdateDTO.getLoginUser(), baseEntity.getManagerConfig(), ProPermissionAliasEnum.KNOWLEDGE_BASE_EDIT);
        if (!permissionsBool) {
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100061);
        }
        List<OptionalRangePojo> viewConfigList = knowledgeBaseUpdateDTO.getViewConfig();
        List<OptionalRangePojo> managerConfigList = knowledgeBaseUpdateDTO.getManagerConfig();
        KnowledgeBaseEntity knowledgeBaseEntity = new KnowledgeBaseEntity();
        knowledgeBaseEntity.setKnowledgeName(knowledgeBaseUpdateDTO.getName());
        String viewConfigString = null;
        if (!Objects.isNull(viewConfigList)) {
            viewConfigString = JSONArray.toJSONString(viewConfigList);
            knowledgeBaseEntity.setViewConfig(viewConfigString);
        }
        String managerConfigString = null;
        if (!Objects.isNull(managerConfigList)) {
            managerConfigString = JSONArray.toJSONString(managerConfigList);
            knowledgeBaseEntity.setManagerConfig(managerConfigString);
        }
        knowledgeBaseEntity.setId(knowledgeBaseUpdateDTO.getId());
        knowledgeBaseEntity.setCorpid(knowledgeBaseUpdateDTO.getCorpid());
        knowledgeBaseModel.update(knowledgeBaseEntity);
        // 更新后记录日志
        addKnowledgeBaseEditLog(knowledgeBaseUpdateDTO, baseEntity, viewConfigString, managerConfigString);
        return new BaseVO();
    }


    @Override
    public BaseVO knowledgeBaseDelete(KnowledgeBaseDetailDTO knowledgeBaseDetailDTO) throws XbbException {
        KnowledgeBaseEntity baseEntity = knowledgeBaseModel.getByKey(knowledgeBaseDetailDTO.getId(), knowledgeBaseDetailDTO.getCorpid());
        if (Objects.isNull(baseEntity)) {
            return new BaseVO();
        }
        if (Objects.equals(baseEntity.getIsDefault(), 1)) {
            throw new XbbException(KnowledgeErrorCodeEnum.API_ERROR_320016.getCode(),KnowledgeErrorCodeEnum.API_ERROR_320016.getMsg());
        }
        // 权限校验
        boolean permissionsBool = permissionsValidation(knowledgeBaseDetailDTO.getLoginUser(), baseEntity.getManagerConfig(), ProPermissionAliasEnum.KNOWLEDGE_BASE_DELETE);
        if (!permissionsBool) {
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100061);
        }
        KnowledgeBaseEntity knowledgeBaseEntity = new KnowledgeBaseEntity();
        knowledgeBaseEntity.setId(knowledgeBaseDetailDTO.getId());
        knowledgeBaseEntity.setCorpid(knowledgeBaseDetailDTO.getCorpid());
        knowledgeBaseEntity.setDel(DelEnum.DELETE.getDel());
        knowledgeBaseModel.update(knowledgeBaseEntity);
        // 删除知识库后，将下面所有的知识条目也删除
        threadPoolBeanConfig.addUpdateDelThreadPool().execute(() -> {
            try {
                knowledgeBaseHelp.deleteKnowledgeBaseByKnowledgeBaseId(knowledgeBaseDetailDTO.getCorpid(), knowledgeBaseDetailDTO.getId());
            } catch (XbbException e) {
                log.error("deleteKnowledgeBaseByBaseIdError,corpid：{}，error：{}", knowledgeBaseDetailDTO.getCorpid(), e);
            }
        });

        // 删除后记录日志
        String memo = knowledgeBaseDetailDTO.getLoginUserName() + I18nMessageUtil.getMessage(CommonConstant.DEL) + String.format(I18nMessageUtil.getMessage(StringConstant.KNOWLEDGE_BASE_LOG), baseEntity.getKnowledgeName());
        mongoLogHelp.buildLog(knowledgeBaseDetailDTO.getCorpid(), knowledgeBaseDetailDTO.getUserId(), knowledgeBaseDetailDTO.getLoginUserName(), OperateModuleTypeEnum.KNOWLEDGE_BASE,
                OperateTypeEnum.DELETE, knowledgeBaseEntity.getId().toString(), baseEntity.getKnowledgeName(), memo, knowledgeBaseDetailDTO.getHttpHeader());
        return new BaseVO();
    }

    @Override
    public BaseVO addKnowledgeCatalogue(KnowledgeCatalogueAddDTO knowledgeCatalogueAddDTO) throws XbbException {
        Long knowledgeId = knowledgeCatalogueAddDTO.getKnowledgeId();
        KnowledgeBaseEntity baseEntity = knowledgeBaseModel.getByKey(knowledgeId, knowledgeCatalogueAddDTO.getCorpid());
        if (Objects.isNull(baseEntity)) {
            throw new XbbException(BiErrorCodeEnum.API_ERROR_241009);
        }
        UserVO loginUser = knowledgeCatalogueAddDTO.getLoginUser();
        boolean isAdminOrBoss = loginUser.isAdminOrBoss();
        if (!isAdminOrBoss) {
            boolean addCatalogueBool = true;
            String managerConfig = baseEntity.getManagerConfig();
            if (StringUtil.isNotEmpty(managerConfig)) {
                List<OptionalRangePojo> optionalRangePojoList = JSONArray.parseArray(managerConfig, OptionalRangePojo.class);
                if (CollectionsUtil.isEmpty(optionalRangePojoList)) {
                    throw new XbbException(SystemErrorCodeEnum.API_ERROR_100061);
                }
                for (OptionalRangePojo optionalRangePojo : optionalRangePojoList) {
                    if (Objects.equals(optionalRangePojo.getId(), knowledgeCatalogueAddDTO.getUserId())) {
                        addCatalogueBool = false;
                    }
                }
                if (addCatalogueBool) {
                    throw new XbbException(SystemErrorCodeEnum.API_ERROR_100061);
                }
            }
        }
        // 目录上限一百个
        Map<String,Object> map = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        map.put(StringConstant.CORPID,knowledgeCatalogueAddDTO.getCorpid());
        map.put("knowledgeId",knowledgeCatalogueAddDTO.getKnowledgeId());
        map.put(StringConstant.DEL,DelEnum.NORMAL.getDel());
        Integer entitysCount = knowledgeCatalogueModel.getEntitysCount(map);
        if (entitysCount >= BasicConstant.KNOWLEDGE_CATALOGUE_HC) {
            throw new XbbException(KnowledgeErrorCodeEnum.API_ERROR_320013.getCode(),KnowledgeErrorCodeEnum.API_ERROR_320013.getMsg());
        }
        // 看看目录名称是否有重复
        map.put("name",knowledgeCatalogueAddDTO.getName());
        Integer count = knowledgeCatalogueModel.getEntitysCount(map);
        if (count >= BasicConstant.ONE) {
            throw new XbbException(KnowledgeErrorCodeEnum.API_ERROR_320018.getCode(),KnowledgeErrorCodeEnum.API_ERROR_320018.getMsg());
        }
        KnowledgeCatalogueEntity knowledgeCatalogueEntity = new KnowledgeCatalogueEntity();
        if (Objects.isNull(knowledgeCatalogueAddDTO.getViewConfig())) {
            knowledgeCatalogueEntity.setViewConfig("[]");
        } else {
            knowledgeCatalogueEntity.setViewConfig(JSONArray.toJSONString(knowledgeCatalogueAddDTO.getViewConfig()));
        }
        knowledgeCatalogueEntity.setKnowledgeId(knowledgeCatalogueAddDTO.getKnowledgeId());
        knowledgeCatalogueEntity.setCorpid(knowledgeCatalogueAddDTO.getCorpid());
        knowledgeCatalogueEntity.setParentId(knowledgeCatalogueAddDTO.getParentId());
        knowledgeCatalogueEntity.setName(knowledgeCatalogueAddDTO.getName());
        knowledgeCatalogueEntity.setCreatorId(knowledgeCatalogueAddDTO.getUserId());
        knowledgeCatalogueEntity.setSort(knowledgeCatalogueAddDTO.getSort());
        knowledgeCatalogueModel.insert(knowledgeCatalogueEntity);
        return new BaseVO();
    }

    @Override
    public KnowledgeCatalogueListVO knowledgeCatalogueList(KnowledgeBaseDetailDTO knowledgeBaseDetailDTO) throws XbbException {
        Long id = knowledgeBaseDetailDTO.getId();
        KnowledgeCatalogueListVO knowledgeCatalogueListVO = new KnowledgeCatalogueListVO();
        // 判断是否拥有编辑,新建权限
        UserVO loginUser = knowledgeBaseDetailDTO.getLoginUser();
        boolean isAdminOrBoss = isAdminOrBossOrKnowledgeAdmin(knowledgeBaseDetailDTO.getCorpid(), id, loginUser);
        String department = loginUser.getDepartment();
        List<String> departmentList = new ArrayList<>();
        if (StringUtil.isNotEmpty(department)){
            departmentList = JSONArray.parseArray(department, String.class);
        }
        knowledgeCatalogueListVO.setEditBool(isAdminOrBoss);
        Map<String, Object> param = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        param.put(StringConstant.CORPID, knowledgeBaseDetailDTO.getCorpid());
        param.put("knowledgeId", id);
        param.put(StringConstant.DEL, DelEnum.NORMAL.getDel());
        param.put("orderByStr", "parent_id asc, sort asc, update_time desc");
        List<KnowledgeCatalogueEntity> knowledgeCatalogueEntityList = knowledgeCatalogueModel.findEntitys(param);
        if (CollectionsUtil.isEmpty(knowledgeCatalogueEntityList)) {
            knowledgeCatalogueListVO.setDepartmentTree(new ArrayList<>());
            return knowledgeCatalogueListVO;
        }
        Map<Long, CataloguePojo> catalogueMap = new LinkedHashMap<>(knowledgeCatalogueEntityList.size());
        // 没有权限查看的id列表
        List<Long> noPermissionsIdList = new ArrayList<>();

        for (KnowledgeCatalogueEntity knowledgeCatalogueEntity : knowledgeCatalogueEntityList) {
            CataloguePojo cataloguePojo = new CataloguePojo();
            cataloguePojo.setValue(knowledgeCatalogueEntity.getId());
            cataloguePojo.setLabel(knowledgeCatalogueEntity.getName());
            cataloguePojo.setParentId(knowledgeCatalogueEntity.getParentId());
            cataloguePojo.setSort(knowledgeCatalogueEntity.getSort());
            // 父目录id为0的数据需要添加上可见范围
            if (Objects.equals(0L, knowledgeCatalogueEntity.getParentId()) && StringUtil.isNotEmpty(knowledgeCatalogueEntity.getViewConfig())) {
                List<OptionalRangePojo> optionalRangePojoList = JSONArray.parseArray(knowledgeCatalogueEntity.getViewConfig(), OptionalRangePojo.class);
                cataloguePojo.setViewConfig(optionalRangePojoList);
            }
            catalogueMap.put(knowledgeCatalogueEntity.getId(), cataloguePojo);
            // 将所有没有权限查看的数据添加到noPermissionsIdList
            if (!isAdminOrBoss && Objects.equals(0L, knowledgeCatalogueEntity.getParentId())
                    && StringUtil.isNotEmpty(knowledgeCatalogueEntity.getViewConfig()) && CollectionsUtil.isNotEmpty(JSONArray.parseArray(knowledgeCatalogueEntity.getViewConfig()))) {
                List<OptionalRangePojo> optionalRangePojoList = JSONArray.parseArray(knowledgeCatalogueEntity.getViewConfig(), OptionalRangePojo.class);
                Set<String> userIdSet = new HashSet<>();
                Set<String> departmentIdSet = new HashSet<>();
                listToString(optionalRangePojoList, userIdSet, departmentIdSet);
                if ((CollectionsUtil.isNotEmpty(userIdSet) && !userIdSet.contains(knowledgeBaseDetailDTO.getUserId()))
                        && Collections.disjoint(departmentList, departmentIdSet)) {
                    noPermissionsIdList.add(knowledgeCatalogueEntity.getId());
                }
            }
        }
        for (Map.Entry<Long, CataloguePojo> entry : catalogueMap.entrySet()) {
            CataloguePojo cataloguePojo = entry.getValue();
            Long parentId = cataloguePojo.getParentId();
            if (catalogueMap.containsKey(parentId)) {
                CataloguePojo parent = catalogueMap.get(parentId);
                parent.addNode(cataloguePojo);
            }
        }
        List<CataloguePojo> cataloguePojoList = catalogueMap.values().parallelStream().filter(s -> "0".equals(s.getParentId().toString())).collect(Collectors.toList());
        // 还需要过滤掉没有权限查看的数据
        if (CollectionsUtil.isNotEmpty(cataloguePojoList) && CollectionsUtil.isNotEmpty(noPermissionsIdList) && !isAdminOrBoss) {
            Iterator<CataloguePojo> iterator = cataloguePojoList.iterator();
            while (iterator.hasNext()) {
                CataloguePojo next = iterator.next();
                if (noPermissionsIdList.contains(next.getValue())) {
                    iterator.remove();
                }
            }
        }
        knowledgeCatalogueListVO.setDepartmentTree(cataloguePojoList);
        return knowledgeCatalogueListVO;
    }


    @Override
    public BaseVO knowledgeCatalogueSort(KnowledgeCatalogueSortDTO knowledgeCatalogueSortDTO) throws XbbException {
        // 跨级拖动排序后，需要将父id修改
        KnowledgeCatalogueEntity knowledgeCatalogueEntity = new KnowledgeCatalogueEntity();
        knowledgeCatalogueEntity.setSort(knowledgeCatalogueSortDTO.getSort());
        knowledgeCatalogueEntity.setCorpid(knowledgeCatalogueSortDTO.getCorpid());
        knowledgeCatalogueEntity.setParentId(knowledgeCatalogueSortDTO.getParentId());
        knowledgeCatalogueEntity.setId(knowledgeCatalogueSortDTO.getId());
        knowledgeCatalogueModel.update(knowledgeCatalogueEntity);
        //还需要将移动到的目录里面的数据重新排序
        Map<String, Object> param = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        param.put(StringConstant.CORPID, knowledgeCatalogueSortDTO.getCorpid());
        param.put("knowledgeId", knowledgeCatalogueSortDTO.getKnowledgeId());
        param.put("parentId", knowledgeCatalogueSortDTO.getParentId());
        param.put("orderByStr", "parent_id asc, sort asc, update_time desc");
        param.put(StringConstant.COLUMNS, "id");
        param.put(StringConstant.DEL, DelEnum.NORMAL.getDel());
        List<KnowledgeCatalogueEntity> knowledgeCatalogueEntityList = knowledgeCatalogueModel.findEntitys(param);
        if (CollectionsUtil.isNotEmpty(knowledgeCatalogueEntityList)) {
            int sort = BasicConstant.ZERO;
            for (KnowledgeCatalogueEntity temp : knowledgeCatalogueEntityList) {
                temp.setSort(sort++);
            }
            knowledgeCatalogueModel.updateBatchSort(knowledgeCatalogueSortDTO.getCorpid(), knowledgeCatalogueEntityList);
        }
        return new BaseVO();
    }

    @Override
    public BaseVO updateKnowledgeCatalogue(KnowledgeCatalogueUpdateDTO knowledgeCatalogueUpdateDTO) throws XbbException {
        Long id = knowledgeCatalogueUpdateDTO.getId();
        String corpid = knowledgeCatalogueUpdateDTO.getCorpid();
        String name = knowledgeCatalogueUpdateDTO.getName();
        // 更新前判断是否有同名元素
        KnowledgeCatalogueEntity catalogueEntity = knowledgeCatalogueModel.getByKey(id, corpid);
        if (Objects.isNull(catalogueEntity)) {
            throw new XbbException(BiErrorCodeEnum.API_ERROR_241009);
        }
        if (!Objects.equals(catalogueEntity.getName(), name)) {
            Map<String, Object> param = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
            param.put(StringConstant.CORPID, corpid);
            param.put("knowledgeId", catalogueEntity.getKnowledgeId());
            param.put("name", name);
            param.put(StringConstant.DEL, DelEnum.NORMAL.getDel());
            Integer entitysCount = knowledgeCatalogueModel.getEntitysCount(param);
            if (entitysCount > BasicConstant.ZERO) {
                throw new XbbException(KnowledgeErrorCodeEnum.API_ERROR_320018.getCode(),KnowledgeErrorCodeEnum.API_ERROR_320018.getMsg());
            }
        }
        KnowledgeCatalogueEntity knowledgeCatalogueEntity = new KnowledgeCatalogueEntity();
        knowledgeCatalogueEntity.setId(id);
        knowledgeCatalogueEntity.setName(name);
        knowledgeCatalogueEntity.setCorpid(corpid);
        List<OptionalRangePojo> viewConfig = knowledgeCatalogueUpdateDTO.getViewConfig();
        if (CollectionsUtil.isEmpty(viewConfig)) {
            knowledgeCatalogueEntity.setViewConfig("[]");
        } else {
            knowledgeCatalogueEntity.setViewConfig(JSONArray.toJSONString(viewConfig));
        }
        knowledgeCatalogueModel.update(knowledgeCatalogueEntity);
        return new BaseVO();
    }

    @Override
    public BaseVO deleteKnowledgeCatalogue(KnowledgeCatalogueDelDTO knowledgeCatalogueDelDTO) throws XbbException {
        String corpid = knowledgeCatalogueDelDTO.getCorpid();
        Long catalogueId = knowledgeCatalogueDelDTO.getCatalogueId();
        Long knowledgeBaseId = knowledgeCatalogueDelDTO.getKnowledgeBaseId();
        // 查询出所有的子目录id
        List<Long> allCatalogueIdList = new ArrayList<>();
        allCatalogueIdList.add(catalogueId);
        knowledgeBaseHelp.getAllChildCatalogueId(corpid, knowledgeBaseId, allCatalogueIdList);
        Map<String, Object> param = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        param.put(StringConstant.CORPID, corpid);
        param.put("knowledgeBaseId", knowledgeBaseId);
        param.put("catalogueIdIn", allCatalogueIdList);
        param.put(StringConstant.DEL, DelEnum.NORMAL.getDel());
        param.put("pageSize", BasicConstant.ONE);
        Integer count = knowledgeDataModel.getEntitysCount(param);
        if (count > BasicConstant.ZERO) {
            throw new XbbException(KnowledgeErrorCodeEnum.API_ERROR_320002.getCode(), KnowledgeErrorCodeEnum.API_ERROR_320002.getMsg());
        }
        Map<String, Object> delMap = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        delMap.put(StringConstant.CORPID, corpid);
        delMap.put("knowledgeId", knowledgeBaseId);
        delMap.put(StringConstant.IDIN, allCatalogueIdList);
        knowledgeCatalogueModel.deleteBatchByIds(delMap);
        return new BaseVO();
    }

    @Override
    public KnowledgeCatalogueListVO knowledgeCatalogueNameLikeQuery(KnowledgeCatalogueNameLikeDTO knowledgeCatalogueNameLikeDTO) throws XbbException {
        KnowledgeCatalogueListVO knowledgeCatalogueListVO = new KnowledgeCatalogueListVO();
        String name = knowledgeCatalogueNameLikeDTO.getName();
        Map<String, Object> param = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        param.put(StringConstant.CORPID, knowledgeCatalogueNameLikeDTO.getCorpid());
        param.put("knowledgeId", knowledgeCatalogueNameLikeDTO.getId());
        if (StringUtil.isNotEmpty(name) && StringUtil.isNotEmpty(name.trim())) {
            param.put("nameLike", name.trim());
        }
        List<KnowledgeCatalogueEntity> knowledgeCatalogueEntityList = knowledgeCatalogueModel.findEntitys(param);
        if (CollectionsUtil.isEmpty(knowledgeCatalogueEntityList)) {
            return knowledgeCatalogueListVO;
        }
        List<CataloguePojo> catalogueList = new ArrayList<>();
        for (KnowledgeCatalogueEntity knowledgeCatalogueEntity : knowledgeCatalogueEntityList) {
            CataloguePojo cataloguePojo = new CataloguePojo();
            cataloguePojo.setValue(knowledgeCatalogueEntity.getId());
            cataloguePojo.setLabel(knowledgeCatalogueEntity.getName());
            catalogueList.add(cataloguePojo);
        }
        knowledgeCatalogueListVO.setDepartmentTree(catalogueList);
        return knowledgeCatalogueListVO;
    }

    @Override
    public KnowledgeHighlighterListVO highlighterList(KnowledgeHighlighterListDTO knowledgeHighlighterListDTO) throws XbbException {
        String corpid = knowledgeHighlighterListDTO.getCorpid();
        Long knowledgeId = knowledgeHighlighterListDTO.getKnowledgeId();
        Long catalogueId = knowledgeHighlighterListDTO.getCatalogueId();
        String name = knowledgeHighlighterListDTO.getName();
        List<Long> label = knowledgeHighlighterListDTO.getLabel();
        UserVO loginUser = knowledgeHighlighterListDTO.getLoginUser();
        TagSortPojo sortPojo = knowledgeHighlighterListDTO.getSortPojo();
        Integer page = knowledgeHighlighterListDTO.getPage();
        Integer pageSize = knowledgeHighlighterListDTO.getPageSize();
        // 根据公司id，知识库id，目录id，标签id精确匹配，根据关键词对标题，关键词，扩展问法，回复文本模糊查询
        KnowledgeHighlighterListVO knowledgeHighlighterListVO = new KnowledgeHighlighterListVO();
        SearchRequest searchRequest = new SearchRequest(IndexTypeEnum.IDX_SAAS_KNOWLEDGE_DATA.getIndex());
        SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();
        BoolQueryBuilder boolQueryBuilder = boolQuery();
        // 判断是否为老板或超管或知识库管理员，如果是，不用添加目录id，如果不是查询到可见的目录id
        boolean isAdminOrBoss = isAdminOrBossOrKnowledgeAdmin(corpid, knowledgeId, loginUser);
        if (!isAdminOrBoss) {
            List<Long> catalogueIdList = knowledgeBaseHelp.getCatalogueIdList(corpid, knowledgeId, loginUser);
            if (CollectionsUtil.isNotEmpty(catalogueIdList)) {
                boolQueryBuilder.filter(termsQuery(KnowledgeDataBaseEnum.CATALOGUE.getAttr(), catalogueIdList));
            } else {
                PageHelper pageHelper = new PageHelper(page, pageSize);
                pageHelper.setRowsCount(0);
                knowledgeHighlighterListVO.setHighlighterList(new ArrayList<>());
                knowledgeHighlighterListVO.setPageHelper(pageHelper);
                return knowledgeHighlighterListVO;
            }
        }
        boolQueryBuilder.filter(termQuery("corpid.keyword", corpid));
        boolQueryBuilder.filter(termQuery("knowledgeBaseId", knowledgeId));
        boolQueryBuilder.filter(termQuery(StringConstant.DEL, DelEnum.NORMAL.getDel()));
        //云呼与企微侧边栏在使用时，需查询启用的数据,0启用1停用
        boolQueryBuilder.filter(termQuery(KnowledgeDataBaseEnum.STATUS.getAttr(), BasicConstant.ZERO));
        if (Objects.nonNull(catalogueId)){
            boolQueryBuilder.filter(termQuery(KnowledgeDataBaseEnum.CATALOGUE.getAttr(), catalogueId));
        }
        if (CollectionsUtil.isNotEmpty(label)){
            boolQueryBuilder.should(termsQuery(KnowledgeDataBaseEnum.LABEL.getAttr(),label).boost(1));
        }
        // 没有选择标签时，查询是否有同名标签，有则添加上
        if (CollectionsUtil.isEmpty(label)) {
            Map<String, Object> map = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
            map.put(StringConstant.CORPID, corpid);
            map.put("name", name);
            map.put(StringConstant.DEL, DelEnum.NORMAL.getDel());
            map.put(StringConstant.COLUMNS, "id");
            List<KnowledgeTagEntity> knowledgeTagEntityList = knowledgeTagModel.findEntitys(map);
            if (CollectionsUtil.isNotEmpty(knowledgeTagEntityList)) {
                List<Long> tagIdList = knowledgeTagEntityList.stream().map(KnowledgeTagEntity::getId).collect(Collectors.toList());
                boolQueryBuilder.should(termsQuery(KnowledgeDataBaseEnum.LABEL.getAttr(),tagIdList).boost(1));
            }
        } else {
            boolQueryBuilder.filter(termsQuery(KnowledgeDataBaseEnum.LABEL.getAttr(), label));
        }
        if (StringUtil.isNotEmpty(name)){
            boolQueryBuilder.should(matchQuery(KnowledgeDataBaseEnum.TITLE.getAttr(),name.trim()).boost(3));
            boolQueryBuilder.should(matchQuery(KnowledgeDataBaseEnum.EXPAND_CONSULT.getAttr(),name.trim()).boost(2));
            boolQueryBuilder.should(matchQuery(KnowledgeDataBaseEnum.KEYWORDS.getAttr(),name.trim()).boost(2));
            boolQueryBuilder.should(matchQuery(KnowledgeDataBaseEnum.CONTENT.getAttr(),name.trim()).boost(1));
            boolQueryBuilder.minimumShouldMatch("1");

        }
        boolQueryBuilder.filter(termQuery(ElasticConstant.MY_JOIN_FIELD, IndexTypeEnum.IDX_SAAS_KNOWLEDGE_DATA.getType()));
        sourceBuilder.query(boolQueryBuilder);
        // 添加默认排序
         if (Objects.isNull(sortPojo)) {
            sourceBuilder.sort("_score", SortOrder.DESC);
        } else {
            SortOrder sortOrder = Objects.equals("desc", sortPojo.getSortType()) ? SortOrder.DESC : SortOrder.ASC;
            sourceBuilder.sort(sortPojo.getSortAttr(), sortOrder);
        }
        EsUtil.setPage(sourceBuilder, page, pageSize);
        //高亮一个片段，一个片段60字，如果没有高亮返回60个字符
        HighlightBuilder highlightBuilder = new HighlightBuilder();
        highlightBuilder.preTags("<em>");
        highlightBuilder.postTags("</em>");
        highlightBuilder.field(KnowledgeDataBaseEnum.TITLE.getAttr());
        highlightBuilder.field(KnowledgeDataBaseEnum.CONTENT.getAttr());
        highlightBuilder.fragmentSize(60);
        highlightBuilder.numOfFragments(1);
        highlightBuilder.noMatchSize(60);
        sourceBuilder.highlighter(highlightBuilder);
        sourceBuilder.fetchSource(new String[]{"id", KnowledgeDataBaseEnum.KEYWORDS.getAttr(), KnowledgeDataBaseEnum.TITLE.getAttr(),KnowledgeDataBaseEnum.LABEL.getAttr()},new String[0]);
        searchRequest.source(sourceBuilder);
        SearchResponse searchResponse = xbbElasticsearchRestTemplate.search(searchRequest);
        //解析返回结果
        SearchHit[] hits = searchResponse.getHits().getHits();
        if (hits == null || hits.length == BasicConstant.ZERO) {
            knowledgeHighlighterListVO.setHighlighterList(new ArrayList<>(BasicConstant.ZERO));
            knowledgeHighlighterListVO.setPageHelper(new PageHelper());
            return knowledgeHighlighterListVO;
        }
        long count = searchResponse.getHits().getTotalHits().value;
        PageHelper pageHelper = new PageHelper(page, pageSize);
        pageHelper.setRowsCount((int) count);
        knowledgeHighlighterListVO.setPageHelper(pageHelper);
        // 组装高亮数据
        List<KnowledgeHighlighterPojo> highlighterList = new ArrayList<>();
        for (int i = BasicConstant.ZERO; i < hits.length; i++) {
            KnowledgeHighlighterPojo knowledgeHighlighterPojo = new KnowledgeHighlighterPojo();
            SearchHit hit = hits[i];
            Map<String, HighlightField> highlightFields = hit.getHighlightFields();
            String sourceAsString = hit.getSourceAsString();
            JSONObject jsonObject = JSONObject.parseObject(sourceAsString);
            Long id = jsonObject.getLong("id");
            JSONArray keywords = jsonObject.getJSONArray(KnowledgeDataBaseEnum.KEYWORDS.getAttr());
            String title = jsonObject.getString(KnowledgeDataBaseEnum.TITLE.getAttr());
            String contentString = jsonObject.getString(KnowledgeDataBaseEnum.CONTENT.getAttr());
            knowledgeHighlighterPojo.setId(id);
            knowledgeHighlighterPojo.setKeywords(keywords);
            HighlightField highlightFieldTitle = highlightFields.get(KnowledgeDataBaseEnum.TITLE.getAttr());
            HighlightField highlightFieldContent = highlightFields.get(KnowledgeDataBaseEnum.CONTENT.getAttr());
            if (Objects.isNull(highlightFieldTitle)) {
                knowledgeHighlighterPojo.setTitle(title);
            } else {
                Text[] fragments = highlightFieldTitle.getFragments();
                if (fragments != null && fragments.length != BasicConstant.ZERO) {
                    StringBuffer titleBuffer = new StringBuffer();
                    for (Text text : fragments) {
                        titleBuffer.append(text);
                    }
                    knowledgeHighlighterPojo.setTitle(titleBuffer.toString());
                } else {
                    knowledgeHighlighterPojo.setTitle(title);

                }
            }
            if (Objects.isNull(highlightFieldContent)) {
                knowledgeHighlighterPojo.setContent(contentString);
            } else {
                Text[] fragments = highlightFieldContent.getFragments();
                if (fragments != null && fragments.length != BasicConstant.ZERO) {
                    StringBuffer temp = new StringBuffer();
                    for (Text text : fragments) {
                        temp.append(text);
                    }
                    knowledgeHighlighterPojo.setContent(temp.toString());
                } else {
                    knowledgeHighlighterPojo.setContent(contentString);
                }
            }
            highlighterList.add(knowledgeHighlighterPojo);
        }
        knowledgeHighlighterListVO.setHighlighterList(highlighterList);
        return knowledgeHighlighterListVO;
    }

    @Override
    public BaseVO hotAutoIncrement(KnowledgeBaseDetailDTO knowledgeBaseDetailDTO) throws XbbException {
        Long id = knowledgeBaseDetailDTO.getId();
        String corpid = knowledgeBaseDetailDTO.getCorpid();
        BaseVO baseVO = new BaseVO();
        KnowledgeDataEntity knowledgeDataEntity = knowledgeDataModel.getByKey(id, corpid);
        if (Objects.isNull(knowledgeDataEntity)) {
            return baseVO;
        }
        long usageCount = knowledgeDataEntity.getUsageCount() + BasicConstant.ONE;
        KnowledgeDataEntity updateEntity = new KnowledgeDataEntity();
        updateEntity.setId(knowledgeDataEntity.getId());
        updateEntity.setCorpid(knowledgeBaseDetailDTO.getCorpid());
        updateEntity.setUsageCount(usageCount);
        knowledgeDataModel.update(updateEntity);

        Map<String, Object> map = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        map.put(StringConstant.UPDATE_TIME, DateTimeUtil.getInt());
        map.put(KnowledgeDataEnum.USAGE_COUNT.getAttr(), usageCount);
        map.put(KnowledgeDataEnum.UPDATE_ID.getAttr(), knowledgeBaseDetailDTO.getUserId());
        InsertDTO insertDTO = new InsertDTO();
        insertDTO.setEsId(corpid + "_" + id);
        insertDTO.setIndexTypeEnum(IndexTypeEnum.IDX_SAAS_KNOWLEDGE_DATA);
        insertDTO.setIndex(IndexTypeEnum.IDX_SAAS_KNOWLEDGE_DATA.getIndex());
        insertDTO.setType(IndexTypeEnum.IDX_SAAS_KNOWLEDGE_DATA.getType());
        insertDTO.setSource(map);
        paasEsModel.update(insertDTO);
        return baseVO;
    }

    @Override
    public KnowledgeHighlighterListVO newKnowledgeData(KnowledgeBaseDetailDTO knowledgeBaseDetailDTO) throws XbbException {
        KnowledgeHighlighterListVO knowledgeHighlighterListVO = new KnowledgeHighlighterListVO();
        SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
        BoolQueryBuilder boolQueryBuilder = boolQuery();
        boolQueryBuilder.filter(termQuery("corpid.keyword", knowledgeBaseDetailDTO.getCorpid()));
        boolQueryBuilder.filter(termQuery("knowledgeBaseId", knowledgeBaseDetailDTO.getId()));
        boolQueryBuilder.filter(termQuery(StringConstant.DEL, DelEnum.NORMAL.getDel()));
        boolQueryBuilder.filter(termQuery("status", 0));
        searchSourceBuilder.query(boolQueryBuilder);
        searchSourceBuilder.sort("usageCount",SortOrder.DESC);
        SearchRequest searchRequest = new SearchRequest(IndexTypeEnum.IDX_SAAS_KNOWLEDGE_DATA.getIndex());
        searchRequest.source(searchSourceBuilder);
        PageRequest pageRequest = EsUtil.setPage(searchSourceBuilder, 0, 10);
        XbbAggregatedPage<KnowledgeDataEntity> knowledgeDataEntityXbbAggregatedPage = xbbElasticsearchRestTemplate.queryForPages(pageRequest, searchRequest, KnowledgeDataEntity.class);
        List<KnowledgeDataEntity> knowledgeDataEntityList = knowledgeDataEntityXbbAggregatedPage.getContent();
        if (CollectionsUtil.isNotEmpty(knowledgeDataEntityList)){
            List<KnowledgeHighlighterPojo> knowledgeHighlighterPojoList = new ArrayList<>(knowledgeDataEntityList.size());
            for (KnowledgeDataEntity knowledgeDataEntity :knowledgeDataEntityList){
                KnowledgeHighlighterPojo knowledgeHighlighterPojo = new KnowledgeHighlighterPojo();
                knowledgeHighlighterPojo.setTitle(knowledgeDataEntity.getTitle());
                knowledgeHighlighterPojoList.add(knowledgeHighlighterPojo);
            }
            knowledgeHighlighterListVO.setHighlighterList(knowledgeHighlighterPojoList);
        }
        return knowledgeHighlighterListVO;
    }

    @Override
    public KnowledgeDetailsVO cloudCallGetDetails(KnowledgeBaseDetailDTO knowledgeBaseDetailDTO) throws XbbException {
        KnowledgeDetailsVO knowledgeContentVO = new KnowledgeDetailsVO();
        String corpid = knowledgeBaseDetailDTO.getCorpid();
        Long id = knowledgeBaseDetailDTO.getId();
        KnowledgeDataEntity knowledgeDataEntity = knowledgeDataModel.getByKey(id,corpid);
        if (Objects.isNull(knowledgeDataEntity)){
            throw new XbbException(KnowledgeErrorCodeEnum.API_ERROR_320017.getCode(),KnowledgeErrorCodeEnum.API_ERROR_320017.getMsg());
        }
        String contentArray = knowledgeDataEntity.getContentArray();
        String expandConsult = knowledgeDataEntity.getExpandConsult();
        String label = knowledgeDataEntity.getLabel();
        List<KnowledgeContentDTO> knowledgeContentDTOList = new ArrayList<>();
        List<String> expandConsultList = new ArrayList<>();
        if (StringUtil.isNotEmpty(contentArray) && CollectionsUtil.isNotEmpty(JSONArray.parseArray(contentArray, KnowledgeContentDTO.class))) {
            knowledgeContentDTOList = JSONArray.parseArray(contentArray, KnowledgeContentDTO.class);
            knowledgeContentDTOList.forEach(e -> e.setContent("<p>" + e.getContent() + "</p>"));
        }
        if (StringUtil.isNotEmpty(expandConsult)){
            expandConsultList = JSONArray.parseArray(expandConsult, String.class);
        }
        knowledgeContentVO.setContentList(knowledgeContentDTOList);
        knowledgeContentVO.setExpandConsultList(expandConsultList);
        List<TagPojo> tagPojoList = new ArrayList<>();
        if (StringUtil.isNotEmpty(label) && CollectionsUtil.isNotEmpty(JSONArray.parseArray(label, Long.class))) {
            List<Long> labelList = JSONArray.parseArray(label, Long.class);
            List<KnowledgeTagEntity> tagModelByTagIdList = knowledgeTagModel.getByTagIdList(labelList, corpid);
            if (CollectionsUtil.isNotEmpty(tagModelByTagIdList)) {
                for (KnowledgeTagEntity knowledgeTagEntity : tagModelByTagIdList) {
                    TagPojo tagPojo = new TagPojo();
                    tagPojo.setId(knowledgeTagEntity.getId());
                    tagPojo.setName(knowledgeTagEntity.getName());
                    tagPojo.setColor(knowledgeTagEntity.getColor());
                    tagPojoList.add(tagPojo);
                }
            }
        }
        knowledgeContentVO.setLabelList(tagPojoList);
        return knowledgeContentVO;
    }


    @Override
    public KnowledgeCloudCallRedirectsVO cloudCallRedirects(BaseDTO baseDTO) throws XbbException {
        KnowledgeCloudCallRedirectsVO knowledgeCloudCallRedirectsVO = new KnowledgeCloudCallRedirectsVO();
        PaasMenuEntity paasMenuEntity = paasMenuModel.getByAlias(ProPermissionAliasEnum.KNOWLEDGE_BASE.getAlias(), baseDTO.getCorpid());
        knowledgeCloudCallRedirectsVO.setAppid(paasMenuEntity.getAppId());
        knowledgeCloudCallRedirectsVO.setMenuId(paasMenuEntity.getId());
        return knowledgeCloudCallRedirectsVO;
    }

    @Override
    public BaseVO baseBatchDelete(KnowledgeBaseBatchDeleteDTO knowledgeBaseBatchDeleteDTO) throws XbbException {
        String corpid = knowledgeBaseBatchDeleteDTO.getCorpid();
        List<Long> idList = knowledgeBaseBatchDeleteDTO.getIdList();
        Map<String, Object> param = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        param.put(StringConstant.CORPID, corpid);
        param.put(StringConstant.IDIN, idList);
        param.put(StringConstant.DEL, DelEnum.NORMAL.getDel());
        List<KnowledgeBaseEntity> knowledgeBaseEntityList = knowledgeBaseModel.findEntitys(param);
        if (CollectionsUtil.isEmpty(knowledgeBaseEntityList)) {
            return new BaseVO();
        }
        for (KnowledgeBaseEntity knowledgeBaseEntity : knowledgeBaseEntityList) {
            // 权限校验
            boolean permissionsBool = permissionsValidation(knowledgeBaseBatchDeleteDTO.getLoginUser(), knowledgeBaseEntity.getManagerConfig(), ProPermissionAliasEnum.KNOWLEDGE_BASE_DELETE);
            if (!permissionsBool) {
                throw new XbbException(SystemErrorCodeEnum.API_ERROR_100061);
            }
        }
        param.remove(StringConstant.IDIN);
        param.remove("isDefault", 0);
        List<KnowledgeBaseEntity> knowledgeBaseEntityAllList = knowledgeBaseModel.findEntitys(param);
        List<Long> selectIdList = new ArrayList<>();
        knowledgeBaseEntityList.forEach(e -> {
            selectIdList.add(e.getId());
        });
        if (CollectionsUtil.isEmpty(knowledgeBaseEntityAllList)) {
            return new BaseVO();
        }
        knowledgeBaseEntityAllList.removeIf(e -> selectIdList.contains(e.getId()));
        knowledgeBaseEntityAllList.forEach(e->{
            e.setDel(DelEnum.DELETE.getDel());
        });
        knowledgeBaseModel.updateBatch(knowledgeBaseEntityAllList,corpid);
        // 删除后记录日志
        StringBuffer knowledgeName = new StringBuffer();
        StringBuffer knowledgeId = new StringBuffer();
        for (int i = 0; i < knowledgeBaseEntityAllList.size(); i++) {
            KnowledgeBaseEntity knowledgeBaseEntity = knowledgeBaseEntityList.get(i);
            knowledgeName.append(knowledgeBaseEntity.getKnowledgeName());
            knowledgeId.append(knowledgeBaseEntity.getId());
            if (i < knowledgeBaseEntityList.size() - 1) {
                knowledgeName.append("，");
                knowledgeId.append("，");
            }
        }
        String memo = knowledgeBaseBatchDeleteDTO.getLoginUserName() + I18nMessageUtil.getMessage(CommonConstant.DEL) + String.format(I18nMessageUtil.getMessage(StringConstant.KNOWLEDGE_BASE_LOG), knowledgeName.toString());
        mongoLogHelp.buildLog(corpid, knowledgeBaseBatchDeleteDTO.getUserId(), knowledgeBaseBatchDeleteDTO.getLoginUserName(), OperateModuleTypeEnum.KNOWLEDGE_BASE,
                OperateTypeEnum.DELETE, knowledgeId.toString(), knowledgeName.toString(), memo, knowledgeBaseBatchDeleteDTO.getHttpHeader());
        return new BaseVO();
    }

    @Override
    public BaseVO homePageShowKnowledge(KnowledgeShowDTO knowledgeShowDTO) throws XbbException {
        String corpid = knowledgeShowDTO.getCorpid();
        String userId = knowledgeShowDTO.getUserId();
        String isShow = Objects.equals(Boolean.TRUE, knowledgeShowDTO.getIsShow()) ? "1" : "0";
        UserConfigEntity userConfigEntity = userConfigModel.getByUserId(userId, corpid, UserConfigEnum.KNOWLEDGE_BASE_SHOW.getAlias());
        if (Objects.isNull(userConfigEntity)) {
            UserConfigEntity inserEntity = new UserConfigEntity();
            inserEntity.setCorpid(knowledgeShowDTO.getCorpid());
            inserEntity.setUserId(knowledgeShowDTO.getUserId());
            inserEntity.setConfigName(UserConfigEnum.KNOWLEDGE_BASE_SHOW.getName());
            inserEntity.setConfigAlias(UserConfigEnum.KNOWLEDGE_BASE_SHOW.getAlias());
            inserEntity.setConfigValue(isShow);
            userConfigModel.insert(inserEntity);
        } else {
            userConfigEntity.setConfigValue(isShow);
            userConfigModel.update(userConfigEntity);
        }
        return new BaseVO();
    }

    /**
     * @param knowledgeBaseDTO
     * @param isDefault
     * @Author mingliang
     * @Description 将knowledgeBaseDTO转换成KnowledgeBaseEntity
     * @Date 2022/6/22 16:54
     **/
    private KnowledgeBaseEntity getEntityByDTO(KnowledgeBaseDTO knowledgeBaseDTO, Integer isDefault) {
        KnowledgeBaseEntity knowledgeBaseEntity = new KnowledgeBaseEntity();
        List<OptionalRangePojo> viewConfigList = knowledgeBaseDTO.getViewConfig();
        List<OptionalRangePojo> managerConfigList = knowledgeBaseDTO.getManagerConfig();
        knowledgeBaseEntity.setCorpid(knowledgeBaseDTO.getCorpid());
        knowledgeBaseEntity.setIsDefault(isDefault);
        knowledgeBaseEntity.setKnowledgeName(knowledgeBaseDTO.getName());
        if (CollectionsUtil.isNotEmpty(viewConfigList)) {
            String viewConfigString = JSONArray.toJSONString(viewConfigList);
            knowledgeBaseEntity.setViewConfig(viewConfigString);
        }
        if (CollectionsUtil.isNotEmpty(managerConfigList)) {
            String managerConfigString = JSONArray.toJSONString(managerConfigList);
            knowledgeBaseEntity.setManagerConfig(managerConfigString);
        }
        knowledgeBaseEntity.setCreatorId(knowledgeBaseDTO.getUserId());
        return knowledgeBaseEntity;
    }


    /**
     * @param baseDTO
     * @Author mingliang
     * @Description 插入默认的知识库
     * @Date 2022/6/22 17:02
     **/
    private void addDefaultKnowledgeBase(BaseDTO baseDTO) {
        KnowledgeBaseEntity knowledgeBaseEntity = new KnowledgeBaseEntity();
        knowledgeBaseEntity.setCreatorId(baseDTO.getUserId());
        knowledgeBaseEntity.setIsDefault(BasicConstant.ONE);
        knowledgeBaseEntity.setCorpid(baseDTO.getCorpid());
        knowledgeBaseEntity.setKnowledgeName(I18nMessageUtil.getMessage(StringConstant.KNOWLEDGE_DEFAULT_NAME));
        knowledgeBaseEntity.setViewConfig("[]");
        knowledgeBaseEntity.setManagerConfig("[]");
        knowledgeBaseModel.insert(knowledgeBaseEntity);
    }


    /**
     * @param loginUser
     * @param managerConfig
     * @param proPermissionAliasEnum
     * @Author mingliang
     * @Description 判断用户是否拥有权限
     * @Date 2022/6/27 14:06
     **/
    private boolean permissionsValidation(UserVO loginUser, String managerConfig, ProPermissionAliasEnum proPermissionAliasEnum) throws XbbException {
        boolean isAdminOrBoss = loginUser.isAdminOrBoss();
        Set<String> managerUserIdSet = new HashSet<>();
        if (StringUtil.isNotEmpty(managerConfig)) {
            List<OptionalRangePojo> optionalRangePojoList = JSONArray.parseArray(managerConfig, OptionalRangePojo.class);
            if (CollectionsUtil.isNotEmpty(optionalRangePojoList)) {
                optionalRangePojoList.forEach(e -> {
                    managerUserIdSet.add(e.getId());
                });
            }
        }
        return isAdminOrBoss || (CollectionsUtil.isNotEmpty(managerUserIdSet) && managerUserIdSet.contains(loginUser.getUserId()) && loginUser.getPermSet().contains(proPermissionAliasEnum.getAlias()));
    }

    /**
     * @param optionalRangePojoList
     * @Author mingliang
     * @Description 将optionalRangePojoList中的name拼接为“张杰，曹操“返回。
     * @Date 2022/6/23 15:46
     **/
    private String listToString(List<OptionalRangePojo> optionalRangePojoList, Set<String> userIdSet, Set<String> departmentIdSet) {
        StringBuffer managerConfigValue = new StringBuffer();
        if (CollectionsUtil.isNotEmpty(optionalRangePojoList)) {
            for (int i = BasicConstant.ZERO; i < optionalRangePojoList.size(); i++) {
                OptionalRangePojo optionalRangePojo = optionalRangePojoList.get(i);
                managerConfigValue.append(optionalRangePojo.getName());
                if (i != optionalRangePojoList.size() - BasicConstant.ONE) {
                    managerConfigValue.append(",");
                }
                if (Objects.equals(optionalRangePojo.getProperty(), "dept") && Objects.nonNull(departmentIdSet)) {
                    departmentIdSet.add(optionalRangePojo.getId());
                } else if (Objects.equals(optionalRangePojo.getProperty(), "user")) {
                    userIdSet.add(optionalRangePojo.getId());
                }
            }
        }
        return managerConfigValue.toString();
    }

    /**
     * @param oldViewConfig
     * @Author mingliang
     * @Description 根据配置人员范围对象获得配置人员姓名String
     * @Date 2022/6/24 14:02
     **/
    private String viewConfigToNameString(String oldViewConfig) {
        StringBuffer logViewConfig = new StringBuffer();
        if (Objects.isNull(oldViewConfig) || Objects.equals(oldViewConfig, "[]")) {
            logViewConfig = new StringBuffer(I18nMessageUtil.getMessage(StringConstant.KNOWLEDGE_All));
        } else {
            List<OptionalRangePojo> optionalRangePojoList = JSONArray.parseArray(oldViewConfig, OptionalRangePojo.class);
            if (CollectionsUtil.isEmpty(optionalRangePojoList)) {
                return logViewConfig.toString();
            }
            for (int i = BasicConstant.ZERO; i < optionalRangePojoList.size(); i++) {
                logViewConfig.append(optionalRangePojoList.get(i).getName());
                if (i < optionalRangePojoList.size() - BasicConstant.ONE) {
                    logViewConfig.append(",");
                }
            }
        }
        return logViewConfig.toString();
    }


    /**
     * @param knowledgeBaseUpdateDTO
     * @param baseEntity
     * @param viewConfigString
     * @param managerConfigString
     * @Author mingliang
     * @Description 知识库更新日志
     * @Date 2022/6/24 14:53
     **/
    private void addKnowledgeBaseEditLog(KnowledgeBaseUpdateDTO knowledgeBaseUpdateDTO, KnowledgeBaseEntity baseEntity, String viewConfigString, String managerConfigString) throws XbbException {
        String oldName = baseEntity.getKnowledgeName();
        String oldViewConfig = baseEntity.getViewConfig();
        String oldManagerConfig = baseEntity.getManagerConfig();
        String newName = knowledgeBaseUpdateDTO.getName();
        List detailArr = new ArrayList();
        if (!Objects.equals(oldName, newName)) {
            DetailLogPojo detailLogPojo = new DetailLogPojo();
            detailLogPojo.setName(I18nMessageUtil.getMessage(StringConstant.KNOWLEDGE_NAME));
            detailLogPojo.setUpdataAfter(newName);
            detailLogPojo.setUpdataBefore(oldName);
            detailArr.add(detailLogPojo);
        }
        if (!Objects.equals(oldViewConfig, viewConfigString)) {
            DetailLogPojo detailLogPojo = new DetailLogPojo();
            detailLogPojo.setName(I18nMessageUtil.getMessage(StringConstant.KNOWLEDGE_VIEW_CONFIG));
            String logViewString = viewConfigToNameString(oldViewConfig);
            String logViewConfigString = viewConfigToNameString(viewConfigString);
            detailLogPojo.setUpdataAfter(logViewConfigString);
            detailLogPojo.setUpdataBefore(logViewString);
            detailArr.add(detailLogPojo);
        }
        if (!Objects.equals(oldManagerConfig, managerConfigString)) {
            DetailLogPojo detailLogPojo = new DetailLogPojo();
            detailLogPojo.setName(I18nMessageUtil.getMessage(StringConstant.KNOWLEDGE_MANAGER_CONFIG));
            String logOldManagerConfig = viewConfigToNameString(oldManagerConfig);
            String logManagerConfigString = viewConfigToNameString(managerConfigString);
            detailLogPojo.setUpdataAfter(logManagerConfigString);
            detailLogPojo.setUpdataBefore(logOldManagerConfig);
            detailArr.add(detailLogPojo);
        }
        String memo = knowledgeBaseUpdateDTO.getLoginUserName() + I18nMessageUtil.getMessage(CommonConstant.EDIT) + String.format(I18nMessageUtil.getMessage(StringConstant.KNOWLEDGE_BASE_LOG), baseEntity.getKnowledgeName());
        if (CollectionsUtil.isNotEmpty(detailArr)) {
            mongoLogHelp.buildLog4DetailArr(detailArr, knowledgeBaseUpdateDTO.getCorpid(), knowledgeBaseUpdateDTO.getUserId(), knowledgeBaseUpdateDTO.getLoginUserName(),
                    OperateModuleTypeEnum.KNOWLEDGE_BASE, OperateTypeEnum.EDIT, baseEntity.getId().toString(), baseEntity.getKnowledgeName(), memo, knowledgeBaseUpdateDTO.getHttpHeader());
        }
    }


    /**
     * @param corpid
     * @param id
     * @param loginUser
     * @Author mingliang
     * @Description 根据公司id，知识库id，判断登录用户是否为老板或超管或者知识库管理员
     * @Date 2022/7/6 10:37
     **/
    private boolean isAdminOrBossOrKnowledgeAdmin(String corpid, Long id, UserVO loginUser) throws XbbException {
        KnowledgeBaseEntity knowledgeBaseEntity = knowledgeBaseModel.getByKey(id, corpid);
        if (Objects.isNull(knowledgeBaseEntity)) {
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100066);
        }
        String managerConfig = knowledgeBaseEntity.getManagerConfig();
        boolean isAdminOrBoss = loginUser.isAdminOrBoss();
        Set<String> managerUserIdSet = new HashSet<>();
        if (StringUtil.isNotEmpty(managerConfig)) {
            List<OptionalRangePojo> optionalRangePojoList = JSONArray.parseArray(managerConfig, OptionalRangePojo.class);
            if (CollectionsUtil.isNotEmpty(optionalRangePojoList)) {
                optionalRangePojoList.forEach(e -> {
                    managerUserIdSet.add(e.getId());
                });
            }
        }
        return isAdminOrBoss || (CollectionsUtil.isNotEmpty(managerUserIdSet) && managerUserIdSet.contains(loginUser.getUserId()));
    }
}
